<?php
namespace app\pays;

use app\models\PayNoticeModel;
use app\models\RechargeManager;
/**
 * 银联支付开发，其他的开发不要在这里 2018-3-7 温宗敏
 */
class WechatPay  extends PayCommon
{
	//微信支付接口地址
	protected $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';

	protected $WechatScanCodeUrl="https://api.mch.weixin.qq.com/pay/micropay";

	protected $pQAppid="wx421d595eacc096ba";
	protected $pQSecret ="bf5a9325b8a4185f5cc0886fea4f9f38";
	
	/**
     * @根据相关的参数获取微信支付链接
	 * @return array 返回的数据
     */
	public function getpayurl($param,$money)
	{
		//判断是否启用了支付
		if ($param['isuse'] != "1"){
			$this->errormsg("未开启支付申请，请联系管理员");
		}
		if($money <= 0){
			$this->errormsg("支付金额必须大于0");
		}
		if(strlen($param['appid'].$param['appsecret'])==0){
			$this->errormsg("商户参数配置错误");
		}
		$result= $this->WechatMd5($param,$money,$this->url,$_SESSION['openid']);//'obTQQvwz-Zr3CDmRye2AqeHzvjvo');
		$this->paylogs('用户进行了微信支付数据请求并成功返回参数');
		return $result;
		
	}

	/**
     * @model 数据库操作对象
	 * @money 需要支付的金额
	 * @exetype 操作类型
     */
	public function ExecuteMethod($model,$money,$exetype,$code="")
	{
		switch($exetype)
		{
			case 'pay':
				//根据签约用户查找微信签约数据
				$result = $model->findwechatmodel($_SESSION['pid']);
				return $this->getpayurl($result[0],$money);
				break;
			case 'subpay'://鹏企下面子商户支付类型
				//根据签约用户查找微信签约数据
				$result = $model->findwechatmodel($_SESSION['pid']);
				return $this->getsubpayurl($result[0],$money);
				break;
			case 'scanpay':
				//根据签约用户查找微信签约数据
				$result = $model->findwechatmodel($_SESSION['pid']);
				return $this->scancodepay($result[0],$money,$code);
				break;
			case 'subscanpay':
				//根据签约用户查找微信签约数据
				$result = $model->findwechatmodel($_SESSION['pid'],true);
				return $this->scancodepay($result[0],$money,$code);
				break;
			case 'scanquery':
				$result = $model->findwechatmodel($_SESSION['pid']);
				return $this->scancodepayquery($result[0],$code);
				break;
			case 'query':
				$this->errormsg('暂未开通微信支付查询');
				break;
			case 'refund':
				$this->errormsg('暂未开通微信支付退款');
				break;
			case 'getopenid':
				$result = $model->findwechatmodel($_SESSION['pid']);
				$openid=$this->GetOpenid($result[0]['appid'],$result[0]['appsecret'])['openid'];
				//如果是微信支付，就先获取用户的openid和key
				$_SESSION['openid']=$openid;
				$_SESSION['key']=$result[0]['key'];
				break;
			case 'sendmsg':
				
				break;
			default:
				$this->errormsg('未能识别微信支付操作类型，请联系管理员');
				break;
		}
	}

	public function RequestUserInfo($usertype)
	{
		switch($usertype)
		{
			case 'wxopenid':
				$data=$this->GetOpenid($this->pQAppid,$this->pQSecret);
				break;
			case 'wxuserinfo':
				$result=$this->GetOpenid($this->pQAppid,$this->pQSecret,'snsapi_userinfo');
				//获取用户信息
				$data=$this->GetWechatUserInfo($result['access_token'],$result['openid']);
				break;
			default:
				$this->errormsg('未能识别微信支付操作类型，请联系管理员');
				break;
		}
		return $data;
	}

	
	public function SendTemplateMessage($account,$store,$money,$desc)
	{
		$userInfo=$this->RequestUserInfo('wxopenid');
		 //设置时间
        $sj = date('Y-m-d H:i:s',time());
		$cz_url = 'http://wx.shpqkj.com';
		//设置发送的消息
        $message = [
            'touser'=>$userInfo['openid'],
            'template_id'=>'8BCgdhkMGcGiFFDRCqySjcD4UI9NtoXochucC_oHFDg',
            'url'=>$cz_url,
            'data'=>[
                'first'=>['value'=>'恭喜您消费成功','color'=>'#173177'],
                'keyword1'=>['value'=>$account,'color'=>'#173177'],
                'keyword2'=>['value'=>$sj,'color'=>'#173177'],
                'keyword3'=>['value'=>$store,'color'=>'#173177'],
                'keyword4'=>['value'=>$money,'color'=>'#173177'],
                'remark'=>['value'=>'如有任何疑问请登录会员系统联系在线客服','color'=>'#173177']
            ]
        ];
		$token=$this->GetToken($this->pQAppid,$this->pQSecret);
		return $this->SendTemplMsg($token,json_encode($message));
	}

	public function SendAuditMessage($title,$number,$company,$dec,$openid)
	{
		 //设置时间
        $sj = date('Y-m-d H:i:s',time());
		$cz_url = 'http://webiae.shpqkj.com/User/AuditByPeople?openid='.$openid.'&hexGuid='.$number;
		//设置发送的消息
        $message = [
            'touser'=>$openid,
            'template_id'=>'eAMXDzgTZ_RZinLt0lxD64fZMjxM9B50Z8h8Vmi8bUQ',
            'url'=>$cz_url,
            'data'=>[
                'first'=>['value'=>$title,'color'=>'#173177'],
                'keyword1'=>['value'=>$number,'color'=>'#173177'],
                'keyword2'=>['value'=>$company,'color'=>'#173177'],
                'keyword3'=>['value'=>$sj,'color'=>'#173177'],
                'remark'=>['value'=>$dec,'color'=>'#173177']
            ]
        ];
		$token=$this->GetToken($this->pQAppid,$this->pQSecret);
		return $this->SendTemplMsg($token,json_encode($message));
	}

	public function SendMatchMessage($title,$number,$len,$dec,$openid,$sid)
	{
		 //设置时间
        $sj = date('Y-m-d H:i:s',time());
		$cz_url = 'http://webiae.shpqkj.com/User/AllotPeople?supplierId='.$sid.'&number='.$number;
		//设置发送的消息
        $message = [
            'touser'=>$openid,
            'template_id'=>'_DmblxAjt3Od1TOXNUwEi7hQnoc-64l--J0Duo3hgiQ',
            'url'=>$cz_url,
            'data'=>[
                'first'=>['value'=>$title,'color'=>'#173177'],
                'keyword1'=>['value'=>$number,'color'=>'#173177'],
                'keyword2'=>['value'=>$sj,'color'=>'#173177'],
                'keyword3'=>['value'=>$len,'color'=>'#173177'],
                'remark'=>['value'=>$dec,'color'=>'#173177']
            ]
        ];
		$token=$this->GetToken($this->pQAppid,$this->pQSecret);
		return $this->SendTemplMsg($token,json_encode($message));
	}


	public function SendSentMessage($sid,$number,$openid,$title,$user,$phone,$address,$totalmoney,$remark)
	{
		//设置时间
        $sj = date('Y-m-d H:i:s',time());
		$cz_url = 'http://webiae.shpqkj.com/User/AllotPeople?supplierId='.$sid.'&number='.$number;
		//设置发送的消息
        $message = [
            'touser'=>$openid,
            'template_id'=>'38eLP4cejg660WgQ-XnhtjqLf5do056DcNT6CZOCSd0',
            'url'=>$cz_url,
            'data'=>[
                'first'=>['value'=>$title,'color'=>'#173177'],
                'keyword1'=>['value'=>$user,'color'=>'#173177'],
                'keyword2'=>['value'=>$phone,'color'=>'#173177'],
                'keyword3'=>['value'=>$address,'color'=>'#173177'],
                'keyword4'=>['value'=>$totalmoney,'color'=>'#173177'],
				'keyword5'=>['value'=>$sj,'color'=>'#173177'],
				'remark'=>['value'=>$remark,'color'=>'#173177']
            ]
        ];
		$token=$this->GetToken($this->pQAppid,$this->pQSecret);
		return $this->SendTemplMsg($token,json_encode($message));
	}
		 


	/**
     * @根据相关的参数获取鹏企服务商下面的子商户支付链接
	 * @return array 返回的数据
     */
	public function getsubpayurl($param,$money)
	{
		//判断是否启用了支付
		if ($param['isuse'] != "1"){
			$this->errormsg("未开启支付申请，请联系管理员");
		}
		if($money <= 0){
			$this->errormsg("支付金额必须大于0");
		}
		if(strlen($param['appid'].$param['appsecret'])==0){
			$this->errormsg("商户参数配置错误");
		}
		$result= $this->SubWechatMd5($param,$money,$this->url,$_SESSION['openid']);//'obTQQvwz-Zr3CDmRye2AqeHzvjvo');
		$this->paylogs('用户进行了微信支付数据请求并成功返回参数');
		return $result;
	}


	public function scancodepay($param,$money,$code)
	{
		//判断是否启用了支付
		if ($param['isuse'] != "1"){
			$this->errormsg("未开启支付申请，请联系管理员");
		}
		if($money <= 0){
			$this->errormsg("支付金额必须大于0");
		}
		if(strlen($param['appid'].$param['appsecret'])==0){
			$this->errormsg("商户参数配置错误");
		}
		$result= $this->WechatScanCodePay($param,$money,$this->WechatScanCodeUrl,$code);
		return $result;
	}
	
	/**
     * @查询支付结果
	 * @param 商户信息
	 * @outcode 支付商户订单号
     */
	public function scancodepayquery($param,$outcode)
	{
		//判断是否启用了支付
		if ($param['isuse'] != "1"){
			$this->errormsg("未开启支付申请，请联系管理员");
		}
		if(strlen($param['appid'].$param['appsecret'])==0){
			$this->errormsg("商户参数配置错误");
		}
		$signkey=$param['key'];
		if(strlen($signkey)==0)
		{
			$this->errormsg("微信支付秘钥不匹配");
		}
		//自定义通用函数
		$arrayParam=array(
			'sub_appid'=>$param['sub_appid'],
			'sub_mch_id'=>$param['sub_mch_id'],
			'appid'=>$param['appid'],
			'mch_id'=>$param['mch_id'],
			'nonce_str'=>$param['mch_id'],
			"out_trade_no" =>$outcode,
			);
		$result= $this->QueryWechatScanPay($arrayParam,$signkey);
		return $result;
	}


	function WechatNotice()
	{
		//创建通知类对象，可以调用方法
		$payResult=new PayNoticeModel();

		$xmlData = file_get_contents('php://input');
		if(strlen($xmlData)==0){
			$this->errormsg("支付通知错误，返回空值");
		}
		
		libxml_disable_entity_loader(true);
		$payresult=json_encode(simplexml_load_string($xmlData, 'SimpleXMLElement', LIBXML_NOCDATA));
		$data = json_decode($payresult,true);
		$this->paylogs('相关数据'.$data['mch_id'].$data['appid'].$data['out_trade_no']);
		if($payResult->findwechatresult($data['mch_id'],$data['appid'],$data['out_trade_no'])!="0"){
			echo '<xml>
					  <return_code><![CDATA[SUCCESS]]></return_code>
					  <return_msg><![CDATA[OK]]></return_msg>
				  </xml>';
			exit();
		}
		ksort($data);
		$buff = '';
		foreach ($data as $k => $v){
			if($k != 'sign'){
				$buff .= $k . '=' . $v . '&';
			}
		}
		//获取本商户的key
		$key = $payResult->findwechatkey($data['appid'],$data['mch_id']);
		if(strlen($key)==0){
			$this->paylogs('未找到微信支付用户的key');
			echo '<xml>
					  <return_code><![CDATA[FAIL]]></return_code>
					  <return_msg><![CDATA[]]></return_msg>
				  </xml>';
			exit();
		}
		$stringSignTemp = $buff . 'key='.$key;//key为证书密钥
		$this->paylogs($stringSignTemp);
		$sign = strtoupper(md5($stringSignTemp));
		//判断算出的签名和通知信息的签名是否一致
		if($sign == $data['sign']){
			$this->paylogs('商户号');
			//把支付结果成功返回记录到数据库中$transaction_id,$out_trade_no,$trade_type
			$payResult->recordwechat($data['openid'],$data['mch_id'],$data['appid'],$data['total_fee'],
				$data['cash_fee'],$data['result_code'],$data['transaction_id'],$data['out_trade_no'],$data['trade_type'],$data['attach'],$data['result_code'],$data['sign']);
			$this->paylogs('商户号：'.$data['mch_id'].'的客户Openid:'.$data['openid'].'支付成功，并正确返回通知结果');
			
			$payinfo=json_decode($data['attach'],true);
			//往卡上充值-微信支付并到芯算卡上充值 type==7是固定的，不要随意修改
			(new RechargeManager())->Invok($data['sign'],$payinfo['type'],$payinfo['p'],$payinfo['c'],$payinfo['n'],$payinfo['o'],$payinfo['pid']);
			//处理完成之后，告诉微信成功结果
			echo '<xml>
					  <return_code><![CDATA[SUCCESS]]></return_code>
					  <return_msg><![CDATA[OK]]></return_msg>
				  </xml>';
		}
		else
		{
			$this->paylogs('微信支付MD验证错误，返回的Sign:'.$data['sign'].'&&&代码验签结果：'.$sign);
			//处理完成之后，告诉微信失败结果
			echo '<xml>
					  <return_code><![CDATA[FAIL]]></return_code>
					  <return_msg><![CDATA[]]></return_msg>
				  </xml>';
			exit();
		}
	}
}